package com.tzstcl.commons.utils;

import com.tzstcl.base.model.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 公司：天筑科技股份有限公司
 * 作者：zgq
 * 日期：2019年02月18日
 * 说明：
 */
@Component
@Slf4j
public class UploadFileUtil {
    /**
     * 本地上传文件路径
     */
    private static String uploadPathLocal;

    /**
     * 本地上传文件路径相对
     */
    private static String uploadPathRelative;

    private static String uploadFileTypes;

    @Value("${project.uploadFileTypes}")
    public void setUploadFileTypes(String uploadFileTypes) {
        UploadFileUtil.uploadFileTypes = uploadFileTypes;
    }

    @Value("${project.uploadFileAbsolutePath}")
    public void setUploadPathLocal(String uploadFilePathLocal) {
        uploadPathLocal = uploadFilePathLocal;
    }

    @Value("${project.uploadFileRelativePath}")
    public void setUploadPathRelative(String uploadFilePathRelative) {
        uploadPathRelative = uploadFilePathRelative;
    }

    public static String getUploadPathLocal() {
        return uploadPathLocal;
    }

    public static String getUploadPathRelative() {
        return uploadPathRelative;
    }

    /**
     * 单个文件保存
     *
     * @param file 文件对象
     * @param type 文件所属模块（相对地址）
     * @return 文件保存后的相对路径
     * @throws IOException
     */
    public static Map<String, Object> saveFile(MultipartFile file, String type) throws IOException {
        if (null == file || file.isEmpty()) {
            return null;
        }
        String datePath = DateUtils.datePath();
        String filePath = "";
        String filePathRelative = "";
        if (StringUtils.isNotBlank(type)) {
            filePath = uploadPathLocal + type + "/" + datePath + "/";
            filePathRelative = uploadPathRelative + type + "/" + "/" + datePath + "/";
        } else {
            filePath = uploadPathLocal + "/" + datePath + "/";
            filePathRelative = uploadPathRelative + "/" + datePath + "/";
        }
        File dir = new File(filePath);
        if (!dir.exists()) {
            FileUtils.forceMkdir(dir);
        }
        String originalFileName = file.getOriginalFilename();
        String ext = originalFileName.substring(originalFileName.lastIndexOf("."));
        String fileName = StringUtils.uuid() + ext;
        filePath = filePath + fileName;
        filePathRelative = filePathRelative + fileName;
        log.debug("文件路径：" + filePath);
        log.debug("相对文件路径：" + filePathRelative);
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(filePath));
        Map<String, Object> result = new HashMap<>();
        result.put("filePath", filePath);
        result.put("fileUrl", filePathRelative);
        return result;
    }


    /**
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @Description //保存多文件
     * @Author liangchen
     * @Date 2019/7/19 16:56
     * @Param [files, type]
     **/
    public static AjaxResult saveFiles(MultipartFile[] files, String type) throws IOException {
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (MultipartFile file : files) {
            if (null == file || file.isEmpty()) {
                return null;
            }
            String originalFileName = file.getOriginalFilename();
            String ext = originalFileName.substring(originalFileName.lastIndexOf("."));
            if (!ArrayUtils.contains(uploadFileTypes.split(","), ext.toLowerCase().substring(1))) {
                return AjaxResult.error("文件类型不允许");
            }
            String filePath = "";
            String filePathRelative = "";
            String datePath = DateUtils.datePath();
            if (StringUtils.isNotBlank(type)) {
                filePath = uploadPathLocal + type + "/" + datePath + "/";
                filePathRelative = uploadPathRelative + type + "/" + "/" + datePath + "/";
            } else {
                filePath = uploadPathLocal + "/" + datePath + "/";
                filePathRelative = uploadPathRelative + "/" + datePath + "/";
            }
            File dir = new File(filePath);
            if (!dir.exists()) {
                FileUtils.forceMkdir(dir);
            }
            String fileName = StringUtils.uuid() + ext;
            filePath = filePath + fileName;
            filePathRelative = filePathRelative + fileName;
            log.debug("文件路径：" + filePath);
            log.debug("相对文件路径：" + filePathRelative);
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(filePath));
            Map<String, Object> result = new HashMap<>();
            result.put("fileName", file.getOriginalFilename());
            result.put("filePath", filePath);
            result.put("fileUrl", filePathRelative);
            result.put("fileType", ext);
            resultList.add(result);
        }
        return AjaxResult.success("上传成功", resultList);
    }


    public static void main(String[] args) {
        String filepath = "E:\\\\zhufile\\技术方案.docx";
//        System.out.println("Extension = " + FilenameUtils.getExtension(filepath));
        System.out.println("Extension = " + FilenameUtils.getName(filepath));
    }
}
